import {
  BeforeInsert,
  Column,
  Entity,
  JoinTable,
  ManyToOne,
  OneToMany,
  PrimaryGeneratedColumn,
} from 'typeorm';
import { Role } from '../../role/entities/role.entity';
import * as bcrypt from 'bcryptjs';
import { Article } from '../../article/entities/article.entity';
import RoleEnum from '../../role/entities/RoleEnum';

@Entity()
export class User {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column({
    type: 'varchar',
    length: 255,
    comment: '用户名',
    unique: true,
  })
  username: string;

  @Column({
    type: 'varchar',
    length: 255,
    comment: '昵称',
    default: '',
  })
  nickname: string;

  @Column({
    type: 'varchar',
    length: 255,
    comment: '密码',
    default: bcrypt.hashSync('123456', 10),
  })
  password: string;

  @Column({ type: 'varchar', length: 255, comment: '电话', default: '' })
  phone: string;

  @Column({ type: 'char', length: 1, comment: '性别', default: '男' })
  gender: string;

  @Column({ type: 'varchar', length: 255, comment: '地址', default: '' })
  address: string;

  @Column({
    type: 'varchar',
    length: 255,
    comment: '邮箱',
    unique: true,
  })
  email: string;

  @Column({ type: 'varchar', length: 255, comment: '头像', default: '' })
  avatar: string;

  @Column({
    type: 'date',
    comment: '出生日期',
    default: () => '(curdate())',
  })
  birthday: Date;

  // 一个用户只能有一个角色
  @ManyToOne(() => Role, (role) => role.users, { nullable: true })
  role: Role;

  @Column({ type: 'varchar', length: 255, comment: '座右铭', default: '' })
  saying: string;

  @Column({
    type: 'datetime',
    default: () => 'CURRENT_TIMESTAMP',
    comment: '创建时间',
  })
  create_time: Date;

  @Column({
    type: 'datetime',
    default: () => 'CURRENT_TIMESTAMP',
    onUpdate: 'CURRENT_TIMESTAMP',
    comment: '更新时间',
  })
  update_time: Date;

  @Column({ type: 'boolean', comment: '是否禁用', default: false })
  is_disabled: boolean;

  @Column({ type: 'boolean', comment: '是否删除', default: false })
  is_deleted: boolean;

  @Column({ type: 'datetime', comment: '禁用时间', default: null })
  disabled_time: Date;

  @Column({ type: 'datetime', comment: '删除时间', default: null })
  delete_time: Date;

  // @Column({ type: 'datetime', comment: '删除时间', default: null })
  // 一个作者多个文章
  @OneToMany(() => Article, (article) => article.author)
  @JoinTable({
    name: 'user_article', // 指定中间表的名称
    joinColumn: {
      name: 'authorId',
      referencedColumnName: 'id',
    },
    inverseJoinColumn: {
      name: 'articleId',
      referencedColumnName: 'id',
    },
  })
  article: Article[];
}
